from django.core.management.base import BaseCommand
from django.db import transaction
from challenge.models import Level, Question, QuestionOption
from challenge.base_questions_data import generate_base_questions


class Command(BaseCommand):
    help = '导入真实题库：12个关卡，每关至少20题，并设置难度标签（支持 --clear 清空后重建）'

    def add_arguments(self, parser):
        parser.add_argument('--clear', action='store_true', help='清空 1-12 关现有题目后再导入')

    @transaction.atomic
    def handle(self, *args, **options):
        if options.get('clear'):
            Question.objects.filter(level__level_id__in=list(range(1, 13))).delete()

        created_levels = 0
        created_questions = 0
        created_options = 0

        for idx in range(1, 13):
            level, level_created = Level.objects.get_or_create(
                level_id=idx,
                defaults={
                    'level_name': f'关卡{idx}',
                    'difficulty_factor': 1.0
                }
            )
            if level_created:
                created_levels += 1

        for item in generate_base_questions():
            level = Level.objects.get(level_id=item['level_id'])
            question = Question.objects.create(
                level=level,
                content=item['content'],
                correct_option_index=item['correct_option_index'],
                difficulty_label=item['difficulty_label']
            )
            created_questions += 1

            for opt in item['options']:
                QuestionOption.objects.create(question=question, content=opt)
                created_options += 1

        self.stdout.write(self.style.SUCCESS(
            f'创建关卡: {created_levels}, 创建题目: {created_questions}, 创建选项: {created_options}'
        ))